//
//  DetailViewController.m
//  LimitFree
//
//  Created by LZXuan on 15-6-9.
//  Copyright (c) 2015年 轩哥. All rights reserved.
//

#import "DetailViewController.h"
#import "AFNetworking.h"
#import "AppModel.h"
#import "DetailModel.h"
#import "UIImageView+WebCache.h"
#import "UIButton+WebCache.h"
#import "PhotosViewController.h"

#import "DBManager.h"


//导入友盟头文件
#import "UMSocial.h"

//导入 具有 短信/邮件模块功能的库
#import <MessageUI/MessageUI.h>

@interface DetailViewController ()<UIActionSheetDelegate,MFMessageComposeViewControllerDelegate,MFMailComposeViewControllerDelegate,UMSocialUIDelegate>

{
    //保存详情model
    DetailModel *_deatailModel;
    NSMutableArray *_modelsArr;
}

@property (weak, nonatomic) IBOutlet UIImageView *iconImageView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UILabel *typeLabel;
@property (weak, nonatomic) IBOutlet UIButton *sharesButton;
- (IBAction)btnClick:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet UIButton *favoriteButton;
@property (weak, nonatomic) IBOutlet UIButton *downloadButton;
@property (weak, nonatomic) IBOutlet UIScrollView *photoScrollView;
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet UIScrollView *appScrollView;


@property (nonatomic,strong) DetailModel *detailModel;
//附近的人使用
@property (nonatomic,strong) NSMutableArray *modelsArr;
@end

@implementation DetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addTitleViewWithTitle:@"应用详情"];
    
    //这里我们 先把界面的轮廓 摆出来 然后等下载完数据之后 再去填充其他数据
    
    //判断应用详情之前是否收藏过
    BOOL isExist = [[DBManager sharedManager] isExistAppForAppId:self.applicationId recordType:kLZXFavorite];
    if (isExist) {
        //收藏过
        self.favoriteButton.enabled = NO;//禁用
        [self.favoriteButton setTitle:@"已收藏" forState:UIControlStateDisabled];
    }else {
        self.favoriteButton.enabled = YES;
        [self.favoriteButton setTitle:@"收藏" forState:UIControlStateNormal];
    }
    
    
    [self downloadDetailData];
    [self downloadNearData];
}
#pragma mark - 详情下载
- (void)downloadDetailData {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = [NSString stringWithFormat:kDetailUrl,self.applicationId];
    __weak typeof(self) weakSelf = self;
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"详情下载完成");
        if (responseObject) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            weakSelf.detailModel = [[DetailModel alloc] init];
            //kvc 赋值
            [weakSelf.detailModel setValuesForKeysWithDictionary:dict];
            
            //进入 详情界面之后 就表示浏览了
            //kLZXBrowses 浏览类型
            BOOL isExist = [[DBManager sharedManager] isExistAppForAppId:self.applicationId recordType:kLZXBrowses];
            //下载详情界面数据之后 如果没有保存过，那么就保存一下
            if (!isExist) {
                //没有浏览过
                //保存到本地
                [[DBManager sharedManager] insertModel:weakSelf.detailModel recordType:kLZXBrowses];
            }
            [weakSelf showDetailWithModel:weakSelf.detailModel];
            
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"详情下载失败");
    }];
}
- (void)showDetailWithModel:(DetailModel *)model {
    [self.iconImageView sd_setImageWithURL:[NSURL URLWithString:model.iconUrl] placeholderImage:[UIImage imageNamed: @"topic_Header"]];
    self.nameLabel.text = model.name;
    NSString *typeString = nil;
    if ([self.category isEqualToString:kLimitType]) {
        typeString = @"限免中";
    }else if ([self.category isEqualToString:kFreeType]) {
        typeString = @"免费中";
    }else if([self.category isEqualToString:kReduceType]) {
        typeString = @"降价中";
    }else {
        typeString = @"热榜中";
    }
    
    self.priceLabel.text = [NSString stringWithFormat:@"原价:￥%.2f %@ %@ MB",model.currentPrice.doubleValue,typeString,model.fileSize];
    self.typeLabel.text = [NSString stringWithFormat:@"类型:%@  评分:%@",model.categoryName,model.starCurrent];
    //不能编辑
    self.textView.editable = NO;
    self.textView.text = model.description;
    
    CGFloat h = self.photoScrollView.frame.size.height;
    CGFloat space = 5;
    CGFloat w = (self.photoScrollView.frame.size.width-6*space)/5;
    
    NSArray *arr = model.photos;
    
    for (NSInteger i = 0; i < arr.count; i++) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(space+(w+space)*i, 0, w, h);
        [button addTarget:self action:@selector(imageClick:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = 201+i;
        //异步下载button 的背景图片用sd
        NSDictionary *imageDict = arr[i];
        [button sd_setBackgroundImageWithURL:[NSURL URLWithString:imageDict[@"smallUrl"]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed: @"topic_Header"]];
        [self.photoScrollView addSubview:button];
    }
    //设置滚动区域范围
    self.photoScrollView.contentSize = CGSizeMake((arr.count+1)*space+arr.count*w+20, h);
}
//相册
- (void)imageClick:(UIButton *)button {
    NSInteger index = button.tag - 201;
    //界面跳转  正向传值 把 选中的索引和 图片数组地址传入
    //点击图片之后 切换到大图片视图
    PhotosViewController *pvc = [[PhotosViewController alloc] init];
    //正向传值
    pvc.curIndex = index;
    pvc.photosArr = self.detailModel.photos;
    
    pvc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:pvc animated:YES];

}


#pragma mark -  附近人下载
- (void)downloadNearData {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    double longitude =  116.344539;
    double latitude = 40.034346;
    NSString *nearUrl = [NSString stringWithFormat:kNearAppUrl,longitude,latitude];
    
    
    __weak typeof(self) weakSelf = self;
    [manager GET:nearUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSArray *arr = dict[@"applications"];
            weakSelf.modelsArr = [[NSMutableArray alloc] init];
            
            NSInteger width = (weakSelf.appScrollView.bounds.size.width - 5*6)/5;
            NSInteger height = weakSelf.appScrollView.bounds.size.height;
            for (NSInteger i = 0; i < arr.count; i++) {
                AppModel *model = [[AppModel alloc] init];
                //kvc 赋值
                [model setValuesForKeysWithDictionary:arr[i]];
                [weakSelf.modelsArr addObject:model];
                
                //创建里面的button
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                button.frame =CGRectMake(5+(width+5)*i, 0, width, height);
                [button addTarget:self action:@selector(iconClick:) forControlEvents:UIControlEventTouchUpInside];
                button.tag = 301+i;
                //异步加载网络图片
                [button sd_setBackgroundImageWithURL:[NSURL URLWithString:model.iconUrl] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed: @"topic_Header"]];
                button.layer.masksToBounds = YES;
                button.layer.cornerRadius = 8;
                
                [weakSelf.appScrollView addSubview:button];
            }
            //设置 滚动区域范围
            weakSelf.appScrollView.contentSize = CGSizeMake(weakSelf.appScrollView.bounds.size.width+20, height);
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"附近的人下载失败");
    }];
    
}
#pragma mark - 附近的人按钮
- (void)iconClick:(UIButton *)button {
    //获取选中的 应用model
    AppModel *model = _modelsArr[button.tag-301];
    //详情跳转
    DetailViewController *detail = [[DetailViewController alloc] init];
    //传值
    detail.applicationId = model.applicationId;
    detail.category = self.category;
    
    [self.navigationController pushViewController:detail animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 分享按钮处理
- (IBAction)btnClick:(UIButton *)sender {
    switch (sender.tag) {
        case 101://分享
        {
            [self shardData];
        }
            break;
        case 102://收藏
        {
            //收藏记录
            NSLog(@"datail:%@",self.detailModel);
            
            [[DBManager sharedManager] insertModel:self.detailModel recordType:kLZXFavorite];
            //点击收藏之后 立即禁用
            self.favoriteButton.enabled = NO;//禁用
            [self.favoriteButton setTitle:@"已收藏" forState:UIControlStateDisabled];
            
        }
            break;
        case 103://下载
        {
            //详情中有一个地址 iTunesUrl-> "https://itunes.apple.com/cn/app/star-trek-trexels/id683978968?mt=8&uo=4"
            //这时 去调用 浏览器或者 AppStore
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.detailModel.itunesUrl]];
            //保存下载 记录
            BOOL isExist = [[DBManager sharedManager] isExistAppForAppId:self.applicationId recordType:kLZXDownloads];
            if (!isExist) {
                //是否保存过下载记录
                [[DBManager sharedManager] insertModel:self.detailModel recordType:kLZXDownloads];
            }
            
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - 分享
- (void)shardData {
#if 0
    //调用系统 app分享
    UIActionSheet  *sheet = [[UIActionSheet alloc] initWithTitle:@"分享" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"短信",@"邮件",@"打电话", nil];
    [sheet showInView:self.view];
#elif 0
    //创建 带短信和邮件功能的视图控制器进行分享
    //使用iOS8的UIActionSheet
    if ([UIDevice currentDevice].systemVersion.doubleValue >= 8.0) {
        UIAlertController *sheet = [UIAlertController alertControllerWithTitle:@"分享" message:@"分享一些数据" preferredStyle:UIAlertControllerStyleActionSheet];
        //取消按钮
        [sheet addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        
        /********************************************/
        //短信按钮
        [sheet addAction:[UIAlertAction actionWithTitle:@"短信分享" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            //点击按钮的行为
           
            /*
             *MFMessageComposeViewController内部具有发短信的功能模块
             */
            if ([MFMessageComposeViewController canSendText]) {
                 //检测硬件 是否具备短信功能
                MFMessageComposeViewController *message = [[MFMessageComposeViewController alloc] init];
                //设置 联系人 （可以同时设置多个）
                message.recipients = @[@"10010",@"10086"];
                //设置标题
                message.subject = @"分享";
                //设置短信内容
                message.body = self.detailModel.itunesUrl;
                
                //如果要处理 短信模块上的按钮
                //设置代理
                message.messageComposeDelegate = self;
                
                
                //还可以发送附件
               // message addAttachmentData:<#(NSData *)#> typeIdentifier:<#(NSString *)#> filename:<#(NSString *)#>
               
                //要用模态跳转 弹出这个视图控制器(message 就是一个导航)
                [self presentViewController:message animated:YES completion:nil];
                
            }else{
                NSLog(@"没有短信功能");
            }
            
        }]];
        /********************************************/
        
        //邮件按钮
        [sheet addAction:[UIAlertAction actionWithTitle:@"邮件分享" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            //邮件按钮的行为
            //检测应用是否支持邮件功能模块
            if ([MFMailComposeViewController canSendMail]) {
                MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
                //设置标题
                [mail setSubject:@"这里有你喜欢的东西哟"];
                //设置联系人
                [mail setToRecipients:@[@"421051332@qq.com",@"lv_zhi_xuan@sina.cn"]];
                //设置内容
                NSString *body = [NSString stringWithFormat:@"亲!点击有惊喜哟:%@",self.detailModel.itunesUrl];
                //是否用html格式
                [mail setMessageBody:body isHTML:YES];
                //设置代理
                mail.mailComposeDelegate = self;
                //增加附件
                //把图片转化为二进制
                NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed: @"icon"]);
                
                [mail addAttachmentData:imageData mimeType:@"image/png" fileName:@"icon.png"];
                
                //模态跳转
                [self presentViewController:mail animated:YES completion:nil];
            }else{
                NSLog(@"没有邮件功能");
            }
            
            
        }]];
         /********************************************/
        
        //模态跳转 actionSheet
        [self presentViewController:sheet animated:YES completion:nil];
        
    }
    
#else
#pragma mark - UM分享
   
    //注意：分享到微信好友、微信朋友圈、微信收藏、QQ空间、QQ好友、来往好友、来往朋友圈、易信好友、易信朋友圈、Facebook、Twitter、Instagram等平台需要参考各自的集成方法
    //如果需要分享回调，请将delegate对象设置self，并实现下面的回调方法
    NSString *body = [NSString stringWithFormat:@"这里有惊喜:%@",self.detailModel.itunesUrl];
    [UMSocialSnsService presentSnsIconSheetView:self
                appKey:@"507fcab25270157b37000010"
             shareText:body
            shareImage:[UIImage imageNamed:@"icon"]
       shareToSnsNames:@[UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToWechatTimeline,UMShareToEmail,UMShareToSms] delegate:self];
    
    
#endif
}
//弹出列表方法presentSnsIconSheetView需要设置delegate为self
-(BOOL)isDirectShareInIconActionSheet
{
    return YES;
}
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的微博平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}





#pragma mark - 系统邮件
/*
 enum MFMailComposeResult {
 MFMailComposeResultCancelled,
 MFMailComposeResultSaved,
 MFMailComposeResultSent,
 MFMailComposeResultFailed
 };
 */
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
    switch (result) {
        case MFMailComposeResultCancelled:
        {
            NSLog(@"被取消");
        }
            break;
        case MFMailComposeResultSaved:
        {
            NSLog(@"保存");
        }
            break;
        case MFMailComposeResultFailed:
        {
            NSLog(@"失败");
        }
            break;
        case MFMailComposeResultSent:
        {
            NSLog(@"发送");
        }
            break;
            
        default:
            break;
    }
    //模态跳转返回
    [controller dismissViewControllerAnimated:YES completion:nil];
    
}


#pragma mark - 短信 模块的协议
/*
 enum MessageComposeResult {
 MessageComposeResultCancelled,
 MessageComposeResultSent,
 MessageComposeResultFailed
 };
 */
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {
    //当 处理 短信模块按钮的时候 会调用
    switch (result) {
        case MessageComposeResultCancelled:
        {
            NSLog(@"短信被取消");
        }
            break;
        case MessageComposeResultSent:
        {
            NSLog(@"短信发送成功");
        }
            break;
        case MessageComposeResultFailed:
        {
            NSLog(@"短信失败");
        }
            break;
            
        default:
            break;
    }
    //模态跳转返回
    [controller dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - ios8之前的actionSheet
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    switch (buttonIndex) {
        case 0:
            //短信
        {
            //可以用 openURL:去调用 系统的app(或者其他的app)
            //@"sms://13838384438" 调用短信app
            // tel://10010  调用 打电话
            //mailto://421051332@qq.com 调用邮箱
            //http://www.baidu.com  浏览器
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms://10086"]];
        }
            break;
        case 1:
        {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto://421051332@qq.com"]];
        }
            break;
        case 2:
        {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://10010"]];
        }
            break;
            
        default:
            break;
    }
}



@end






